package id.co.shuba.spamobile.activities;

import java.io.File;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.R.layout;
import id.co.shuba.spamobile.R.menu;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.task.BaseProgressTask;
import id.co.shuba.spamobile.task.DownloadMasterOfflineTask;
import id.co.shuba.spamobile.task.DownloadOfflineTask;
import id.co.shuba.spamobile.task.DownloadUpdateTask;
import id.co.shuba.spamobile.task.OnDownloadCompleteListener;
import id.co.shuba.spamobile.task.OnProgressChangedListener;
import id.co.shuba.spamobile.task.OnStatusChangedListener;
import android.os.Bundle;
import android.os.Environment;
import android.service.textservice.SpellCheckerService.Session;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;

public class UpdateMasterOfflineActivity extends SherlockActivity {
	private DownloadMasterOfflineTask _task;
	private DatabaseHandler _db;
	private TextView txtMessage;
	private ProgressBar pb;
	
	private boolean _gotoMain;
	
	private boolean _finish = false;
	
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
	
	@Override
	protected void onDestroy() {		
		unregisterReceiver(logoutReceiver);
		super.onDestroy();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update);		
		setUpLogoutReceiver();
		
		String file = getIntent().getStringExtra("FILE");
		if (file == null) {
			file = App.getOfflineUpdatePath("master.spapkg").getPath();
		}		
		
		_gotoMain = getIntent().hasExtra("GOTO_MAIN");
		
		_db = new DatabaseHandler(this);		
		
		String message = "Downloading data...";
		
		txtMessage = (TextView) findViewById(R.id.txtMessage);
		txtMessage.setText(message);
		pb = (ProgressBar) findViewById(R.id.progressBar);
		pb.setIndeterminate(false);
		pb.setMax(100);
		
		Object obj = getLastNonConfigurationInstance();									
		
		if (obj == null) {
			UserInfo user = Sessions.getUser(this);
			_task = new DownloadMasterOfflineTask(_db.getWritableDatabase(), user.getAoCode());			
			_task.execute(new File(file), user.getNip());				
		} else {
			_task = (DownloadMasterOfflineTask)obj;			
		}		
		setListener();
	}
	
	private void setListener() {
		
		_task.setProgressChangedListener(new OnProgressChangedListener() {			
			@Override
			public void onProgressChanged(int progress) {
				pb.setProgress(progress);							
			}					
		});
		
		_task.setOnDownloadCompleteListener(new OnDownloadCompleteListener() {
			
			@Override
			public void onDownloadComplete(Exception ex) {
				if (ex != null) {
					Toast.makeText(UpdateMasterOfflineActivity.this,
							ex.getMessage(), Toast.LENGTH_LONG).show();					
				} else {
					Toast.makeText(UpdateMasterOfflineActivity.this,
							"Download berhasil", Toast.LENGTH_LONG).show();												
				}
				
				if (_gotoMain) {					
					Intent intent = new Intent(UpdateMasterOfflineActivity.this, MainActivity.class);
					
					File trans = App.getOfflineUpdatePath("update.spapkg");
					if (trans.exists()) {
						intent = new Intent(UpdateMasterOfflineActivity.this, UpdateOfflineActivity.class);
						intent.putExtra("FILE", trans.getPath());
						intent.putExtra("GOTO_MAIN", true);														
					} 
					
					startActivity(intent);
					
					finish();
				}				
			}
		});
		
		_task.setStatusListener(new OnStatusChangedListener() {			
			@Override
			public void onStatusChanged(final String status) {				
				txtMessage.post(new Runnable() {					
					@Override
					public void run() {
						txtMessage.setText(status);
					}
				});
			}
		});		
	}
		
	@Override
	public Object onRetainNonConfigurationInstance() {		
		_task.setProgressChangedListener(null);
		_task.setOnDownloadCompleteListener(null);
		_task.setStatusListener(null);
		return _task;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		//getSupportMenuInflater().inflate(R.menu.activity_update, menu);
		return true;
	}

}
